using System;
using System.Collections.Generic;
using System.IO;

namespace roster.Domain
{
    public class PlayerFile
    {
        private readonly string m_FileName;

        public PlayerFile(string fileName)
        {
            m_FileName = fileName;
        }

        public RosterDetails GetPlayers()
        {
            using (var reader = new StreamReader(m_FileName))
            {
                StripTimeStamp(reader);
                string title = reader.ReadLine();
                return new RosterDetails(title, GetPlayers(reader));
            }
        }

        private static void StripTimeStamp(TextReader reader)
        {
            reader.ReadLine();
        }

        private static IEnumerable<IPlayer> GetPlayers(StreamReader reader)
        {
            var players = new List<IPlayer>();
            while (!reader.EndOfStream)
            {
                string[] playerInfo = reader.ReadLine().Split(',');
                players.Add(new Player(playerInfo[0], (Class) Enum.Parse(typeof (Class), playerInfo[1]),
                                       DateTime.Parse(playerInfo[2])));
            }
            return players;
        }

        public void WritePlayers(RosterDetails details)
        {
            using (var writer = new StreamWriter(m_FileName, false))
            {
                writer.WriteLine(DateTime.Now);
                writer.WriteLine(details.Title);
                foreach (IPlayer player in details.Players)
                {
                    writer.WriteLine("{0},{1},{2}", player.Name, player.Class, player.LastAttendance.ToShortDateString());
                }
            }
        }
    }
}